// src/screens/main/ActivityHistoryScreen.tsx
import React, { useState, useEffect, useCallback } from 'react';
import {
    View,
    Text,
    StyleSheet,
    FlatList,
    TouchableOpacity,
    RefreshControl,
    ActivityIndicator,
    TextInput,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import LinearGradient from 'react-native-linear-gradient';
import aiService from '../../services/aiService';
import type { StackNavigationProp } from '@react-navigation/stack';
import type { MainStackParamList } from '../../navigation/MainNavigator';

type NavigationProp = StackNavigationProp<MainStackParamList>;

interface ActivityItem {
    id: string;
    type: 'chat' | 'translate' | 'voice';
    title: string;
    subtitle?: string;
    time: string;
    screen: keyof MainStackParamList;
    params?: any;
    data?: any; // 原始数据
}

type FilterType = 'all' | 'chat' | 'translate' | 'voice';

const ActivityHistoryScreen: React.FC = () => {
    const navigation = useNavigation<NavigationProp>();
    const [activities, setActivities] = useState<ActivityItem[]>([]);
    const [filteredActivities, setFilteredActivities] = useState<ActivityItem[]>([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [filter, setFilter] = useState<FilterType>('all');
    const [searchQuery, setSearchQuery] = useState('');
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);

    useEffect(() => {
        loadActivities(true);
    }, []);

    useEffect(() => {
        filterActivities();
    }, [activities, filter, searchQuery]);

    const formatTime = (timestamp?: string | Date): string => {
        if (!timestamp) return '未知时间';

        const date = new Date(timestamp);
        const now = new Date();
        const diff = now.getTime() - date.getTime();

        const minutes = Math.floor(diff / (1000 * 60));
        const hours = Math.floor(diff / (1000 * 60 * 60));
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));

        if (minutes < 1) return '刚刚';
        if (minutes < 60) return `${minutes}分钟前`;
        if (hours < 24) return `${hours}小时前`;
        if (days < 30) return `${days}天前`;

        return date.toLocaleDateString('zh-CN');
    };

    const loadActivities = async (reset = false) => {
        if (loading) return;

        const currentPage = reset ? 1 : page;
        setLoading(true);

        try {
            const activities: ActivityItem[] = [];

            // 并发加载不同类型的历史记录
            const promises = [];

            // 聊天历史
            promises.push(
                aiService.getChatHistory(undefined, currentPage, 10).then(result => {
                    result.messages
                        .filter(msg => msg.role === 'user')
                        .forEach((msg, index) => {
                            activities.push({
                                id: `chat_${msg.id || `${currentPage}_${index}`}`,
                                type: 'chat',
                                title: msg.content.length > 50 ? `${msg.content.substring(0, 50)}...` : msg.content,
                                subtitle: `对话ID: ${msg.conversationId}`,
                                time: formatTime(msg.timestamp),
                                screen: 'ChatDetail',
                                params: { conversationId: msg.conversationId },
                                data: msg,
                            });
                        });
                }).catch(console.warn)
            );

            // 翻译历史
            promises.push(
                aiService.getTranslationHistory(currentPage, 10).then(result => {
                    result.translations.forEach((translation, index) => {
                        activities.push({
                            id: `translate_${translation.id || `${currentPage}_${index}`}`,
                            type: 'translate',
                            title: translation.sourceText.length > 50 ? `${translation.sourceText.substring(0, 50)}...` : translation.sourceText,
                            subtitle: `${translation.sourceLang} → ${translation.targetLang}`,
                            time: formatTime(translation.createdAt),
                            screen: 'TranslateDetail',
                            params: { translationId: translation.id },
                            data: translation,
                        });
                    });
                }).catch(console.warn)
            );

            // 语音历史
            promises.push(
                aiService.getVoiceHistory(currentPage, 10).then(result => {
                    result.records.forEach((record, index) => {
                        activities.push({
                            id: `voice_${record.id || `${currentPage}_${index}`}`,
                            type: 'voice',
                            title: record.text.length > 50 ? `${record.text.substring(0, 50)}...` : record.text,
                            subtitle: `时长: ${Math.round(record.duration)}秒`,
                            time: formatTime(record.createdAt),
                            screen: 'VoiceDetail',
                            params: { recordId: record.id },
                            data: record,
                        });
                    });
                }).catch(console.warn)
            );

            await Promise.all(promises);

            // 按时间排序
            activities.sort((a, b) => {
                const timeA = a.data?.timestamp || a.data?.createdAt || 0;
                const timeB = b.data?.timestamp || b.data?.createdAt || 0;
                return new Date(timeB).getTime() - new Date(timeA).getTime();
            });

            if (reset) {
                setActivities(activities);
                setPage(2);
            } else {
                setActivities(prev => [...prev, ...activities]);
                setPage(prev => prev + 1);
            }

            setHasMore(activities.length >= 10); // 如果返回的数据少于10条，说明没有更多了
        } catch (error) {
            console.error('Load activities error:', error);
        } finally {
            setLoading(false);
        }
    };

    const filterActivities = () => {
        let filtered = activities;

        // 按类型过滤
        if (filter !== 'all') {
            filtered = filtered.filter(item => item.type === filter);
        }

        // 按搜索关键词过滤
        if (searchQuery.trim()) {
            const query = searchQuery.trim().toLowerCase();
            filtered = filtered.filter(item =>
                item.title.toLowerCase().includes(query) ||
                (item.subtitle && item.subtitle.toLowerCase().includes(query))
            );
        }

        setFilteredActivities(filtered);
    };

    const onRefresh = useCallback(async () => {
        setRefreshing(true);
        setPage(1);
        await loadActivities(true);
        setRefreshing(false);
    }, []);

    const loadMore = useCallback(() => {
        if (hasMore && !loading && filteredActivities.length > 0) {
            loadActivities();
        }
    }, [hasMore, loading, filteredActivities]);

    const handleActivityPress = (activity: ActivityItem) => {
        try {
            if (activity.params) {
                navigation.navigate(activity.screen, activity.params);
            } else {
                navigation.navigate(activity.screen as any);
            }
        } catch (error) {
            console.warn('Navigation error:', error);
        }
    };

    const getTypeIcon = (type: string): string => {
        switch (type) {
            case 'chat': return 'chat';
            case 'translate': return 'translate';
            case 'voice': return 'mic';
            default: return 'history';
        }
    };

    const getTypeColor = (type: string): string => {
        switch (type) {
            case 'chat': return '#667eea';
            case 'translate': return '#f093fb';
            case 'voice': return '#4facfe';
            default: return '#999';
        }
    };

    const getTypeName = (type: string): string => {
        switch (type) {
            case 'chat': return '聊天';
            case 'translate': return '翻译';
            case 'voice': return '语音';
            default: return '未知';
        }
    };

    const filters: { key: FilterType; label: string; count: number }[] = [
        { key: 'all', label: '全部', count: activities.length },
        { key: 'chat', label: '聊天', count: activities.filter(a => a.type === 'chat').length },
        { key: 'translate', label: '翻译', count: activities.filter(a => a.type === 'translate').length },
        { key: 'voice', label: '语音', count: activities.filter(a => a.type === 'voice').length },
    ];

    const renderActivityItem = ({ item }: { item: ActivityItem }) => (
        <TouchableOpacity
            style={styles.activityItem}
            onPress={() => handleActivityPress(item)}
            activeOpacity={0.7}
        >
            <View style={[styles.activityIcon, { backgroundColor: `${getTypeColor(item.type)}15` }]}>
                <Icon name={getTypeIcon(item.type)} size={24} color={getTypeColor(item.type)} />
            </View>
            <View style={styles.activityContent}>
                <View style={styles.activityHeader}>
                    <Text style={styles.activityTitle} numberOfLines={2}>
                        {item.title}
                    </Text>
                    <Text style={styles.activityTime}>{item.time}</Text>
                </View>
                {item.subtitle && (
                    <Text style={styles.activitySubtitle} numberOfLines={1}>
                        {item.subtitle}
                    </Text>
                )}
                <View style={styles.activityFooter}>
                    <View style={styles.typeTag}>
                        <Text style={[styles.typeText, { color: getTypeColor(item.type) }]}>
                            {getTypeName(item.type)}
                        </Text>
                    </View>
                </View>
            </View>
            <Icon name="chevron-right" size={24} color="#ccc" />
        </TouchableOpacity>
    );

    const renderHeader = () => (
        <View>
            {/* 搜索框 */}
            <View style={styles.searchContainer}>
                <Icon name="search" size={20} color="#999" style={styles.searchIcon} />
                <TextInput
                    style={styles.searchInput}
                    placeholder="搜索历史记录..."
                    value={searchQuery}
                    onChangeText={setSearchQuery}
                    placeholderTextColor="#999"
                />
                {searchQuery.length > 0 && (
                    <TouchableOpacity onPress={() => setSearchQuery('')}>
                        <Icon name="clear" size={20} color="#999" />
                    </TouchableOpacity>
                )}
            </View>

            {/* 过滤器 */}
            <View style={styles.filtersContainer}>
                {filters.map((filterItem) => (
                    <TouchableOpacity
                        key={filterItem.key}
                        style={[
                            styles.filterButton,
                            filter === filterItem.key && styles.filterButtonActive
                        ]}
                        onPress={() => setFilter(filterItem.key)}
                    >
                        <Text style={[
                            styles.filterText,
                            filter === filterItem.key && styles.filterTextActive
                        ]}>
                            {filterItem.label} ({filterItem.count})
                        </Text>
                    </TouchableOpacity>
                ))}
            </View>
        </View>
    );

    const renderEmpty = () => (
        <View style={styles.emptyContainer}>
            <Icon name="history" size={64} color="#ccc" />
            <Text style={styles.emptyTitle}>
                {searchQuery ? '未找到相关记录' : '暂无使用记录'}
            </Text>
            <Text style={styles.emptySubtitle}>
                {searchQuery ? '尝试使用其他关键词搜索' : '开始使用AI功能，记录将显示在这里'}
            </Text>
        </View>
    );

    const renderFooter = () => {
        if (!loading) return null;

        return (
            <View style={styles.loadingContainer}>
                <ActivityIndicator size="small" color="#667eea" />
                <Text style={styles.loadingText}>加载中...</Text>
            </View>
        );
    };

    return (
        <View style={styles.container}>
            <FlatList
                data={filteredActivities}
                keyExtractor={(item) => item.id}
                renderItem={renderActivityItem}
                ListHeaderComponent={renderHeader}
                ListEmptyComponent={renderEmpty}
                ListFooterComponent={renderFooter}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        onRefresh={onRefresh}
                        colors={['#667eea']}
                    />
                }
                onEndReached={loadMore}
                onEndReachedThreshold={0.1}
                showsVerticalScrollIndicator={false}
                contentContainerStyle={styles.listContent}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f8f9fa',
    },
    listContent: {
        flexGrow: 1,
    },
    searchContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderRadius: 25,
        paddingHorizontal: 15,
        paddingVertical: 10,
        marginHorizontal: 20,
        marginVertical: 15,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 3.84,
        elevation: 5,
    },
    searchIcon: {
        marginRight: 10,
    },
    searchInput: {
        flex: 1,
        fontSize: 16,
        color: '#333',
    },
    filtersContainer: {
        flexDirection: 'row',
        paddingHorizontal: 20,
        paddingBottom: 15,
        gap: 10,
    },
    filterButton: {
        paddingHorizontal: 16,
        paddingVertical: 8,
        borderRadius: 20,
        backgroundColor: '#fff',
        borderWidth: 1,
        borderColor: '#e0e0e0',
    },
    filterButtonActive: {
        backgroundColor: '#667eea',
        borderColor: '#667eea',
    },
    filterText: {
        fontSize: 14,
        color: '#666',
    },
    filterTextActive: {
        color: '#fff',
        fontWeight: '500',
    },
    activityItem: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        padding: 15,
        marginHorizontal: 20,
        marginBottom: 10,
        borderRadius: 12,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 3.84,
        elevation: 5,
    },
    activityIcon: {
        width: 50,
        height: 50,
        borderRadius: 25,
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: 15,
    },
    activityContent: {
        flex: 1,
    },
    activityHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'flex-start',
        marginBottom: 4,
    },
    activityTitle: {
        fontSize: 16,
        fontWeight: '600',
        color: '#333',
        flex: 1,
        marginRight: 10,
    },
    activityTime: {
        fontSize: 12,
        color: '#999',
    },
    activitySubtitle: {
        fontSize: 14,
        color: '#666',
        marginBottom: 8,
    },
    activityFooter: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    typeTag: {
        paddingHorizontal: 8,
        paddingVertical: 2,
        borderRadius: 10,
        backgroundColor: '#f0f0f0',
    },
    typeText: {
        fontSize: 11,
        fontWeight: '500',
    },
    emptyContainer: {
        alignItems: 'center',
        justifyContent: 'center',
        paddingVertical: 60,
    },
    emptyTitle: {
        fontSize: 18,
        fontWeight: '600',
        color: '#666',
        marginTop: 15,
    },
    emptySubtitle: {
        fontSize: 14,
        color: '#999',
        marginTop: 8,
        textAlign: 'center',
        paddingHorizontal: 40,
    },
    loadingContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        paddingVertical: 20,
    },
    loadingText: {
        marginLeft: 10,
        fontSize: 14,
        color: '#666',
    },
});

export default ActivityHistoryScreen;